function _addZero(value) {
  return value < 10 ? ('0' + value) : value;
}

//获取图标里显示日期数值
function getIconDate(type) {
  const date = new Date();

  switch (type) {
    case 'day':
      //补零
      return _addZero(date.getDate().toString());
    case 'month':
      return _addZero((date.getMonth() + 1).toString());
    case 'year':
      //2019 -> 19
      //取后两位
      return date.getFullYear().toString().substr(2);
  }
}

////2020-7-9 -> 2020年7月9日
function formatChineseDate(date, type) {
  const _arr = date.split('-');

  switch (type) {
    case 'day':
      return `${_arr[0]}年${_arr[1]}月${_arr[2]}日`;
    case 'month':
      return `${_arr[0]}年${_arr[1]}月`;
    case 'year':
      return `${_arr[0]}年`;
    default:
      return `${_arr[0]}年${_arr[1]}月${_arr[2]}日`;
  }
}

/**
 * holidaylist: [
 *   {\"name\":\"元旦\",\"startday\":\"2018-1-1\"},
 *   {\"name\":\"除夕\",\"startday\":\"2018-2-15\"},
 *   ..
 * ]
 */
function mapForChineseDate(data, key) {
  // console.log(key); year-month/saturday
  return data.map((item) => {
    item[key] = formatChineseDate(item[key]);
    return item;
  })
}

function getNowDate(field) {
  const date = new Date();

  let year = date.getFullYear(),
    month = date.getMonth() + 1,
    day = date.getDate();

  switch (field) {
    case 'day':
      return `${year}-${month}-${day}`;
    case 'month':
      return `${year}-${month}`;
    case 'year':
      return `${year}`;
    default:
      return `${year}-${month}-${day}`;
  }
}

//将用户搜索输入框输入的日期格式化
//20150503 -> 2015-5-3
//201803 -> 2018-3
//2019 -> 2019
function formatUserDate(value) {
  const len = value.length;

  if (len < 4) {
    return;
  }

  //年份 不需要处理
  if (len === 4) {
    return value;
  }

  //201803 -> 2018-3
  if (len > 4 && len < 6) {
    return value.substr(0, 4);
  }

  //20150503 -> 2015-5-3
  let _arr = [],
    pattern;
  if (len >= 6 && len < 8) {
    //匹配规则：数字前4位为一组,数字后两位为一组
    pattern = /(\d{4})(\d{2})/;
    //2018-3
    value = value.substr(0, 6).replace(pattern, '$1-$2');

    _arr = Array.from(value).filter((item, index) => {
      //2018-03 去掉0
      if (index === 5 && item === '0') {
        return false;
      }
      return true;
    })
  }

  if (len >= 8) {
    //年月日
    pattern = /(\d{4})(\d{2})(\d{2})/;
    value = value.substr(0, 8).replace(pattern, '$1-$2-$3');

    _arr = Array.from(value).filter((item, index) => {
      //2018-03-05 去掉0
      if ((index === 5 || index === 8) && item === '0') {
        return false;
      }
      return true;
    })
  }

  //[2,0,1,8,-,3,-,5] -> 2018-3-5
  return _arr.toString().replace(/,/g, '');
}

export {
  getIconDate,
  formatChineseDate,
  mapForChineseDate,
  getNowDate,
  formatUserDate
}